﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
using System.Text;
using MobileAPI.Common;

namespace MobileAPI.Web.Data
{
    /// <summary>
    /// 返回给移动端的通信消息
    /// </summary>
    public class MobileRspMsg : BaseMobileMsg
    {
        public MobileRspMsg()
            : base()
        {

        }

        public MobileRspMsg(MobileReqMsg req)
            : this()
        {
            this.MsgFormat = req.MsgFormat;

            this.Head.APICode = req.Head.APICode;
            this.Head.UseGZip = req.Head.UseGZip;
        }

        /// <summary>
        /// 使用 GZip 对 Body 内容进行压缩
        /// </summary>
        /// <returns></returns>
        public byte[] Compress()
        {
            this.Head.ToXml(this.MobileXml.Head);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(this.MobileXml.ToXml());

            // 压缩 Body 节点
            XmlNode node = doc.SelectSingleNode("//Body");
            byte[] bytes = GZipUtils.Compress(Encoding.UTF8.GetBytes(node.InnerXml));
            node.InnerXml = MobileCryptoUtil.ToHexString(bytes);

            if (this.MsgFormat == EMobileMsgFormat.Json)
            {
                return Encoding.UTF8.GetBytes(MobileJsonConverter.ToJosn(doc));
            }
            else
            {
                return Encoding.UTF8.GetBytes(doc.OuterXml);
            }
        }
    }
}